package com.benjaminwan.read.free.ui.guide

import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.airbnb.mvrx.MvRx
import com.airbnb.mvrx.activityViewModel
import com.airbnb.mvrx.withState
import com.benjaminwan.read.free.R
import com.benjaminwan.read.free.base.fragment.BaseFragment
import com.benjaminwan.read.free.base.viewmodel.state
import com.benjaminwan.read.free.common.singleTopNavOptions
import com.benjaminwan.read.free.databinding.FragmentGuideBinding
import com.benjaminwan.read.free.ui.settings.SettingsViewModel
import com.benjaminwan.read.free.utils.argsNullable

class GuideFragment : BaseFragment() {

    private val settingsVM by activityViewModel(SettingsViewModel::class)

    companion object {
        fun arg(isBooting: Boolean): Bundle {
            val args = Bundle()
            args.putBoolean(MvRx.KEY_ARG, isBooting)
            return args
        }
    }

    private val isBooting by argsNullable<Boolean>()

    private lateinit var binding: FragmentGuideBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentGuideBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (isBooting != null && isBooting == true) {
            val isShow = settingsVM.state.isShowGuide
            if (!isShow) {
                findNavController().navigate(R.id.operationFragment, null, singleTopNavOptions)
            }
        }
        initViews()
    }

    private fun initViews() {
        binding.guideTv.text = Html.fromHtml(
            getString(R.string.guide_first_html),
            Html.FROM_HTML_MODE_COMPACT
        )
        binding.isShowStv.setCheckBoxCheckedChangeListener { compoundButton, isChecked ->
            settingsVM.setIsShowGuide(isChecked)
        }
        binding.isShowStv.setOnClickListener {
            val isShow = settingsVM.state.isShowGuide
            settingsVM.setIsShowGuide(!isShow)
        }
    }

    override fun invalidate() = withState(settingsVM) { settings ->
        binding.isShowStv.setCheckBoxChecked(settings.isShowGuide, true)
        Unit
    }

}